package com.sh.personnel.security.config.filter;
import com.sh.personnel.config.redis.RedisConstant;
import com.sh.personnel.security.exception.CaptchaValidateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录验证码验证过滤器
 * @author 林思浩
 * @date 2020/03/11 23:43
 */
@Component
public class LoginCaptchaAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if("/api/login".equalsIgnoreCase(request.getRequestURI())
                && "POST".equalsIgnoreCase(request.getMethod())) {
            try {
                validateCaptcha(request);
            } catch (CaptchaValidateException e) {
                authenticationFailureHandler.onAuthenticationFailure(request, response, e);return;
            }
        }
        filterChain.doFilter(request, response);

    }

    /**
     * 验证验证码
     * @param request
     */
    private void validateCaptcha(HttpServletRequest request) {
        String key = getCaptchaKey(request);
        String code = getCaptchaCode(request);
        if(StringUtils.isEmpty(key)) throw new CaptchaValidateException("验证码已过期");
        if(StringUtils.isEmpty(code)) throw new CaptchaValidateException("验证码不能为空");
        String value = (String) redisTemplate.opsForValue().get(RedisConstant.LOGIN_CAPTCHA + key);
        if(StringUtils.isEmpty(value)) throw new CaptchaValidateException("验证码已过期");
        if(!code.equalsIgnoreCase(value)) throw new CaptchaValidateException("验证码错误");

    }

    /**
     * 获取图片验证码key
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request) {
        return request.getParameter("captcha_key");
    }

    /**
     * 获取验证码code
     * @param request
     * @return
     */
    private String getCaptchaCode(HttpServletRequest request) {
        return request.getParameter("captcha_code");
    }

}
